package my.geraltigas.week6_springboot.dao.impl;

import my.geraltigas.week6_springboot.dao.GoodsDAO;
import my.geraltigas.week6_springboot.entity.Goods;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

@Component
public class GoodDAOImpl implements GoodsDAO {
    List<Goods> dataBase;

    public GoodDAOImpl() {
        dataBase = new LinkedList<>();
        add(new Goods(1, "apple", "苹果好吃", 1));
        add(new Goods(2, "banana", "香蕉也不错", 2));
    }

    @Override
    public List<Goods> list() {
        return dataBase;
    }

    @Override
    public Goods get(int id) {
        for (Goods goods : dataBase) {
            if (goods.getId() == id) {
                return goods;
            }
        }
        return null;
    }

    @Override
    public int add(Goods goods) {
        dataBase.add(goods);
        return 1;
    }

    @Override
    public int update(Goods goods) {
        for (Goods goods1 : dataBase) {
            if (goods1.getId() == goods.getId()) {
                goods1.setName(goods.getName());
                goods1.setPrice(goods.getPrice());
                goods1.setDescription(goods.getDescription());
                return 1;
            }
        }
        return 0;
    }

    @Override
    public int delete(int id) {
        for (Goods goods : dataBase) {
            if (goods.getId() == id) {
                dataBase.remove(goods);
                return 1;
            }
        }
        return 0;
    }
}

